const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let type 		= req.body.type;
	let medicine_id = req.body.medicine_id;
	let clerk_id 	= req.body.clerk_id;
	let message 	= req.body.message;
	let remarks 	= req.body.remarks;

	let sql = '';
	let params = [];
	let sqlArr = [];


	if (req.session.type == "clerk") {
		clerk_id = req.session.id;
	}

	if (type != undefined) {
		sqlArr.push(' type = ?');
		params.push(type);
	}

	if (medicine_id != undefined) {
		sqlArr.push(' medicine_id = ?');
		params.push(medicine_id);
	}

	if (clerk_id != undefined) {
		sqlArr.push(' clerk_id = ?');
		params.push(clerk_id);
	}

	if (message != undefined) {
		sqlArr.push(' message LIKE ?');
		message = '%' + message + '%';
		params.push(message);
	}

	if (remarks != undefined) {
		sqlArr.push(' remarks LIKE ?');
		remarks = '%' + remarks + '%';
		params.push(remarks);
	}

	if (sqlArr.length == 0) {
		sql = 'SELECT b.id as id, create_time, b.type as type, b.amout as amout, message, remarks, medicine_id, m.name as medicine_name, clerk_id, c.name as clerk_name FROM bill b LEFT JOIN clerk c ON b.clerk_id = c.id LEFT JOIN medicine m ON b.medicine_id = m.id;'
	} else {
		var sql2 = '';
		for (var j = 0; j<sqlArr.length; j++) {
			sql2 += sqlArr[j] + 'and'
		}
		sql2 = sql2.slice(0, -3);
		sql = 'SELECT b.id as id, create_time, b.type as type, b.amout as amout, message, remarks, medicine_id, m.name as medicine_name, clerk_id, c.name as clerk_name FROM bill b LEFT JOIN clerk c ON b.clerk_id = c.id LEFT JOIN medicine m ON b.medicine_id = m.id WHERE' + sql2 + ';';
	}


	pool.getConnection(function(err, connection) {
		if (err) { 
			sendResponse('error','database error', null, res);
			return;
		}

		connection.query(sql, params, function (error, rows, fields) {

			connection.release();

			if (error) { 
				sendResponse('error',error, null, res);
			} else {
				let result = {
					data: rows
				}
				sendResponse('ok','success', result, res);
			}
			return ;
		})	

	});

}